<template>
  <a-form ref="formRef" :model="formState" :rule="formRules" class="login-form">
    <a-typography-text strong id="title">登录</a-typography-text>
    <a-form-item
      has-feedback
      label="用户"
      name="username"
      :rules="formRules.username"
    >
      <a-input
        v-model:value="formState.username"
        autocomplete="off"
        placeholder="请输入用户名"
        class="a-input"
      >
        <template #prefix>
          <UserOutlined />
        </template>
      </a-input>
    </a-form-item>

    <a-form-item
      has-feedback
      label="密码"
      name="password"
      :rules="formRules.password"
    >
      <a-input-password
        v-model:value="formState.password"
        autocomplete="off"
        placeholder="请输入密码"
        class="a-input"
      >
        <template #prefix>
          <LockOutlined />
        </template>
      </a-input-password>
    </a-form-item>

    <a-form-item>
        <a-checkbox v-modek:value="formState.check">记住我</a-checkbox>
    </a-form-item>

    <a-form-item>
      <a-button
        type="primary"
        :loading="isLoading"
        @click="submitForm"
        id="login-button"
        >提交</a-button
      >
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue";
import type { FormInstance } from "ant-design-vue";
import type { Rule } from "ant-design-vue/es/form";
import { message } from "ant-design-vue";
import { useLoginStore } from "../store/loginStore";
import { HTTP_STATUS } from "../api/request";
import { useRouter } from "vue-router";

const router = useRouter()

const loginStore = useLoginStore();

interface FormState {
  username: string;
  password: string;
  check: boolean
}

const formState = ref<FormState>({
  username: "",
  password: "",
  check: false
});

const formRef = ref<FormInstance>();

//按钮加载状态
const isLoading = ref<boolean>(false);

//提交表单
function submitForm() {
  formRef.value
    ?.validate()
    .then((valid) => {
      if (valid) {
        isLoading.value = true;
        setTimeout(async () => {
          try {
            const res = await loginStore.requestLogin({
              username: formState.value.username,
              password: formState.value.password,
              isRememberMe: formState.value.check,
            });
            if (res.status === HTTP_STATUS.SUCCESS) {
              message.success(res.msg + ", 跳转中")
              setTimeout(() => {
                router.push("/")
              },1000)
            }
          } catch (error) {
            
          } finally {
            isLoading.value = false;
          }
        });
      }
    })
    .catch(() => {
      message.error("登录失败，请检查输入信息是否正确");
      isLoading.value = false;
    })
}

//验证用户名是否合法
const validateUsername = async (_rule: Rule, value: string) => {
  if (value === "" || /^\s*$/.test(value)) {
    return Promise.reject("请输入用户名");
  } else if (/\S\s\S/.test(value)) {
    return Promise.reject("用户名中间不能包含空格");
  }
  return Promise.resolve();
};

//验证密码是否合法
const validatePassword = async (_rule: Rule, value: string) => {
  if (value === "" || /^\s*$/.test(value)) {
    return Promise.reject("请输入密码");
  } else if (value.includes(" ")) {
    return Promise.reject("密码不能包含空格");
  }
  // callback()
  return Promise.resolve();
};

//配置校验规则
const formRules: Record<string, Rule[]> = {
  username: [{ validator: validateUsername, trigger: "blur", required: true }],
  password: [{ validator: validatePassword, trigger: "blur", required: true }],
};
</script>

<style lang="scss" scoped>
.login-form {
  border: 1px solid rgba(205, 198, 198, 0.957);
  border-radius: 10px;
  width: 450px;
  box-shadow: 0px 5px 10px #cccc;
  height: 180 px;
  vertical-align: middle;
  text-align: center;
  font-weight: bolder;

  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  justify-content: center;
  align-items: center;

  #title {
    font-size: large;
  }

  span , label{
    user-select: none
  }
}

.a-input {
  width: 250px;
}

#login-button {
  user-select: none;
  width: 300px;
}
</style>
